<script setup>

import mqtt from 'mqtt'
import api from './api.js'
import TitleLabel from "@/components/TitleLabel.vue";
import dateUtil from '@/utils/date.js'

const { proxy } = getCurrentInstance();

const tableRef = ref();

const openFlag = ref(false);
const messageList = ref([]);
const deviceList = ref([]);

const emit = defineEmits(['sub']);


let host = window.location.hostname;

let client;

function findExistMsg(msg) {
  return messageList.value.find(item=> {
    return item.tag === msg;
  });
}

function insertIntoMessageList(msg) {
  let existMsg = findExistMsg(msg);
  if (existMsg) {
    existMsg.time = new Date();
  } else {
    messageList.value.splice(0, 0, {
      tag: msg,
      time: new Date()
    });
  }

}

function createWebsocket() {
  client = mqtt.connect(`tcp://${host}:61614`);
  client.on('connect', function () {
    console.log('已连接到 MQTT Broker');
  });

  client.on('message', function (topic, message) {
    const msg = message.toString();
    console.log(`收到消息: ${msg} 来自主题: ${topic}`);
    insertIntoMessageList(msg);
  });

  client.on('error', function (err) {
    console.error('错误:', err);
  });

  client.on('close', function () {
    console.log('关闭mqtt连接');
  })

  client.on('end', function () {
    console.log('End mqtt连接');
  })
}


let lastUuid = null;

/**
 * 订阅mqtt主题
 * @param uuid
 */
function subscribe(uuid) {
  // 订阅主题前，把上次的主题订阅取消掉
  unsubscribeLast();
  const topic = `device/${uuid}/tag`;
  client.subscribe(topic, { qos: 1 }, function (err, granted) {
    if (!err) {
      console.log(`${uuid}已成功订阅`);
    }
  });
}

/**
 * 取消订阅mqtt主题
 * @param uuid
 */
function unsubscribe(uuid) {
  if (lastUuid) {
    client.unsubscribe(`device/${uuid}/tag`);
  }
}

function unsubscribeLast() {
  if (lastUuid) {
    unsubscribe(lastUuid);
  }
}

function deviceRead(device) {
  deviceList.value.forEach(item=> {
    item.running = false;
  })
  const uuid = device.number;
  device.running = true;
  subscribe(uuid);
  // 发送盘点请求
  startInventory(uuid);
  lastUuid = uuid;
}

function deviceStopRead(device) {
  const uuid = device.number;
  device.running = false;
  // 去掉消息订阅
  unsubscribe(uuid);
  // 发送盘点请求
  stopInventory(uuid);
  lastUuid = null;
}

function closeWebsocket() {
  if (client) {
    client.end();
  }
}

function startInventory(uuid) {
  api.inventory(uuid).then(response => {
    proxy.$modal.msgSuccess("RFID读取");
  })
}

function stopInventory(uuid) {
  api.stopInventory(uuid).then(response => {
    proxy.$modal.msgSuccess("停止RFID读取");
  })
}

function stopLastInventory() {
  if (lastUuid) {
    stopInventory(lastUuid);
  }
}

function sub() {
  const current = tableRef.value.getCurrentRecord();
  debugger
  emit('sub', current.tag);
  close();
}

async function getDeviceList() {
  const l = await api.list();
  if (l.length > 0) {
    l[0].selected = true;
  }
  deviceList.value = l;
  return deviceList;
}

function open() {
  // 创建WebSocket监听RFID的读取
  openFlag.value = true;
  messageList.value = [];
  createWebsocket();
  getDeviceList();

}

function close() {
  openFlag.value = false;
}

function onClose() {
  stopLastInventory();
  closeWebsocket();
}

// 外部使用的属性或方法
defineExpose({
  open
})
</script>

<template>

  <div>
    <el-dialog width="500" height="500" title="RFID读卡" v-model="openFlag" align-center top="50" @close="onClose">
      <title-label>用户设备</title-label>
      <ul>
        <li v-for="d in deviceList">
          <div class="device-list">
            <div class="content">
              <span class="breath-light" :class="{'active': d.running}"></span>
              {{ d.name }}
            </div>
            <div>
              <el-button v-if="!d.running" size="small" @click="deviceRead(d)">读取</el-button>
              <el-button v-else size="small" @click="deviceStopRead(d)">停止</el-button>
            </div>
          </div>
        </li>
      </ul>
      <div style="height: 300px">
        <vxe-table ref="tableRef" :data="messageList" height="auto" :row-config="{isCurrent: true, isHover: true}">

          <vxe-column field="tag" title="标签"></vxe-column>
          <vxe-column field="time" title="时间">
            <template #default="{ row }">
              {{dateUtil.formatDate(row.time)}}
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-row type="flex" justify="end">
          <el-button @click="sub">确定</el-button>
          <el-button @click="close">取消</el-button>
        </el-row>
      </div>
    </el-dialog>
  </div>


</template>

<style scoped lang="scss">
.device-list {
  display: flex;
  width: 100%;
  .content {
    flex-grow: 1;
  }
  .buttons {
    flex-shrink: 0;
  }
}
</style>